package com.zy.openchat.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.ja.openchat.R;
import com.zy.openchat.App;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class Common {

    public static String getPasswordFloodIntervalStr(int password_flood_interval){
        StringBuilder builder = new StringBuilder();
        if(password_flood_interval<60){
            builder.append(password_flood_interval);
            builder.append(" ");
            builder.append(App.getInstanse().getString(R.string.second_text));
        }else if(password_flood_interval<3600){
            int m = password_flood_interval/60;
            int s = password_flood_interval%60;
            builder.append(m);
            builder.append(" ");
            builder.append(App.getInstanse().getString(R.string.minute_text));
            if(s>0){
                builder.append(s);
                builder.append(" ");
                builder.append(App.getInstanse().getString(R.string.second_text));
            }
        }else{
            int h = password_flood_interval/360;
            int balance = password_flood_interval%360;
            int m = balance/60;
            int s = balance%60;
            builder.append(h);
            builder.append(" ");
            builder.append(App.getInstanse().getString(R.string.hour_text));
            if(m>0){
                builder.append(m);
                builder.append(" ");
                builder.append(App.getInstanse().getString(R.string.minute_text));
            }
            if(s>0){
                builder.append(s);
                builder.append(" ");
                builder.append(App.getInstanse().getString(R.string.second_text));
            }
        }
        return builder.toString();
    }
    //格式化价格
    public static String formatPrice(float price) {
        return new DecimalFormat("0.00").format(price);
    }

    public static String MD5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(text.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String md5 = number.toString(16);

            while (md5.length() < 32)
                md5 = "0" + md5;

            return md5;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String toUtf16(String str) {
        String result = null;
        try {
            result = new String(str.getBytes("UTF-16"), "UTF-16");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static String formatPhoneNumber(String phone){
        if(TextUtils.isEmpty(phone)){
            return "";
        }
        PhoneNumberUtil numberUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber phoneNumber = numberUtil.parse(!phone.contains("+")?("+"+phone):phone, Phonenumber.PhoneNumber.CountryCodeSource.UNSPECIFIED.name());
            return numberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
        }catch (NumberParseException exception){
            return phone;
        }
    }

    public static void showSoftKeyboard(View view) {
        if (view == null) return;
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        if (!view.isFocused()) view.requestFocus();

        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, 0);
    }

    public static boolean isEmpty(List<?> list){
        return list==null||list.size()==0;
    }

    public static String getCurrentFormatTime() {
        return new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    }

    public static final SimpleDateFormat BIRTH = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public static int getAgeByBirth(String birthday){
        try {
            return getAgeByBirth(BIRTH.parse(birthday));
        }catch (Exception e){

        }
        return 0;
    }

    public static int getAgeByBirth(Date birthday){
        //Calendar：日历
        /*从Calendar对象中或得一个Date对象*/
        Calendar cal = Calendar.getInstance();
        /*把出生日期放入Calendar类型的bir对象中，进行Calendar和Date类型进行转换*/
        Calendar bir = Calendar.getInstance();
        bir.setTime(birthday);
        /*如果生日大于当前日期，则抛出异常：出生日期不能大于当前日期*/
        if(cal.before(birthday)){
            return 0;
        }
        /*取出当前年月日*/
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayNow = cal.get(Calendar.DAY_OF_MONTH);
        /*取出出生年月日*/
        int yearBirth = bir.get(Calendar.YEAR);
        int monthBirth = bir.get(Calendar.MONTH);
        int dayBirth = bir.get(Calendar.DAY_OF_MONTH);
        /*大概年龄是当前年减去出生年*/
        int age = yearNow - yearBirth;
        /*如果出当前月小与出生月，或者当前月等于出生月但是当前日小于出生日，那么年龄age就减一岁*/
        if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
            age--;
        }
        return age;
    }

    public static String getMetaDataByKey(String key) {

        String placeholdersValues = "";
        try {
            ApplicationInfo appInfo = App.getInstanse().getPackageManager()
                    .getApplicationInfo(App.getInstanse().getPackageName(),
                            PackageManager.GET_META_DATA);
            if (appInfo == null) {
                return "";
            }
            Bundle metaData = appInfo.metaData;
            if (metaData == null) {
                return "";
            }
            placeholdersValues = metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return placeholdersValues;
    }

}
